package cn.tb.ymcc.mq.consumer;

import cn.tb.ymcc.domain.CourseOrder;
import cn.tb.ymcc.dto.PayNotifyDto;
import cn.tb.ymcc.service.ICourseOrderService;
import cn.tb.ymcc.util.AssertUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@RocketMQMessageListener(
        consumerGroup = "pay-notify-order-consumer",
        topic = "pay-notify-topic",
        selectorExpression = "pay-notify-tag",
        messageModel = MessageModel.BROADCASTING  //默认是集群模式，一个消息只会被一个消费者消费
)
public class PayNotifyOrderConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private ICourseOrderService courseOrderService;

    /**
     * 修改订单状态
     * @param messageExt
     */
    @Override
    public void onMessage(MessageExt messageExt) {
        byte[] body = messageExt.getBody();
        if(body == null){
            return;
        }
        String s = new String(body, StandardCharsets.UTF_8);
        PayNotifyDto payNotifyDto = JSONObject.parseObject(s, PayNotifyDto.class);
        CourseOrder courseOrder = courseOrderService.selectOrderByOrderNo(payNotifyDto.getOrderNo());
        AssertUtil.isNotNull(courseOrder,"订单不存在");
        courseOrderService.updatePayOrder(courseOrder);
    }
}
